/*
 * @Author: SailorCai
 * @Date: 2020-12-07 22:29:25
 * @LastEditors: SailorCai
 * @LastEditTime: 2020-12-08 00:04:30
 * @FilePath: /chat/client/src/views/Chat/index.tsx
 */
import React from 'react'
import { NavBar } from 'antd-mobile';
import Icon from '@/components/font'
import { connect } from 'react-redux'
import { useHistory } from 'react-router-dom'
import {useState, useEffect} from 'react'
import { TextareaItem, Button } from 'antd-mobile';
import { getUserInfo } from '@/api/common'
import './Chat.less' 
const qs = require('qs');

export type ChatUser = {
  name: string
} 
export type ChatProp = {
  user: ChatUser
}

function Chat(props: any) {
  const query = qs.parse(window.location.search, { ignoreQueryPrefix: true });
  const {chats, updateMsg, clearMsgStatus} = props;
  clearMsgStatus({id: query.id});
  const history = useHistory();
  const [text, setText]:[string, any] = useState('');
  const [user, setUser] : [any, any] = useState({});
  useEffect(() => {
    if(!user._id) {
      fetchUserInfo();
    };
  });
  async function fetchUserInfo() {
    if(query.id === 'hall') {
      return setUser({username: '大厅', _id: 'hall'})
    }
    const res = await getUserInfo({_id: query.id});
    setUser(res.data);
  };
  function textChg(e: any) {
    setText(e.target.value);
  };
  function backClick() {
    history.goBack();
  };
  function send() {
    const msgObj = {msg: text, from: (window as any).$ctx};
    setText('');
    let currChatId = query.id === 'hall' ? 'hall' : (window as any).$ctx.id;
    (window.io as any).emit(query.id, JSON.stringify({[currChatId]: msgObj}))
    
    updateMsg({[query.id]: msgObj});
  };
  return (
    <div className="f-col chat-wrapper">
      <NavBar 
        mode="light" 
        rightContent={
          <div className="head-right">
            <Icon type="icon-ellipsis-vertical"></Icon>
          </div>
        }
        leftContent={(
          <>
            <div className="icon-back-left">
              <Icon type="icon-angle-left" onClick={backClick}></Icon>
            </div>
            {user.username}
          </>
        )}>
      </NavBar>
      <section className="f-grow text-wrapper">
        <div className="content-scroll">
          {
            chats[query.id] && chats[query.id].map((res: any, index: any) => <ChatText key={res.msg+index} data={res} />)
          }
        </div>
      </section>
      <section className="f-row chat-bottom">
        <Icon type="icon-WIFI"></Icon>
        <TextareaItem
          className="f-grow"
          data-seed="logId"
          autoHeight
          value={text}
          onInput={textChg}
        />
        <Icon type="icon-wind-smile"></Icon>
        {
          text ? <Button onClick={send} type="primary" size="small">发送</Button> : <Icon type="icon-plus-circle"></Icon>
        }
      </section>
    </div>
  )
}


function ChatText(props:any) {
  const {data} = props;
  return (
    <div className={data.from.id === (window as any).$ctx.id ? 'chat_history f-row self' : 'chat_history f-row'}>
      <span className="header">{data.from.username}</span>
      <span className="text">{data.msg}</span>
    </div>
  )
}


export default connect(state => {
  return {
    user: (state as any).chator,
    chats: (state as any).hallChat
  };
}, dispatch => {
  return {
    updateMsg(payload:any) {
      dispatch({type: 'update_hall', payload})
    },
    clearMsgStatus(payload: any) {
      dispatch({type: 'clearMsgStatus', payload})
    }
  }
})(Chat);
